package com.lvmama.pet.sync.service.util;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.lang3.StringUtils;
import org.elasticsearch.common.settings.ImmutableSettings;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;

import com.lvmama.comm.sync.po.SyncElasticsearch;
import com.lvmama.pet.sync.service.SyncElasticsearchServiceImpl;

public class ESWrapper {

	/**
	 * @param pengfei
	 */
	private static Log log = LogFactory.getLog(ESWrapper.class);
    private static Map<String,Client> clientMap =  new ConcurrentHashMap<String, Client>();
   	
	
    public static synchronized Client getClient(String esCode) {
        Client client = null;

    	SyncElasticsearch syncElasticsearch= null;
    	List<SyncElasticsearch> list =  SyncElasticsearchServiceImpl.syncElasticsearchInit;
    	for (SyncElasticsearch _syncElasticsearch : list) {
			if(StringUtils.isNotEmpty(_syncElasticsearch.getEsCode())&&StringUtils.isNotEmpty(esCode)&&_syncElasticsearch.getEsCode().equals(esCode)){
				syncElasticsearch=_syncElasticsearch;
			}
		}
    	if(list!=null&&list.size()>0){
    		String esHost =  syncElasticsearch.getIpPort();
        	String clusterName = syncElasticsearch.getClusterName();
        		if(StringUtils.isNotEmpty(esHost) && StringUtils.isNotEmpty(clusterName)){
        			String[] esNodes = esHost.split(",");
        			if(clientMap.get(esCode) == null){
        				try {
        					Settings settings = ImmutableSettings.settingsBuilder().put("cluster.name",clusterName).put("client.transport.sniff", true).build();
        					client = new TransportClient(settings);
        					for (String ips : esNodes) {
        						String[] ipPort = ips.split("\\:");
    						    ((TransportClient) client).addTransportAddress(new InetSocketTransportAddress(ipPort[0], Integer.parseInt(ipPort[1])));
    						}
        				} catch (Exception e) {
        					log.error("ElasticSearch  init failed ，the reason ["+e.getMessage()+"]");
        				}
        				clientMap.put(esCode, client);
        			}
        		}else{
        			log.error("the es server host or clusterName  is required！，can not found the argument");
        		}
    	}
    	
    	
    	
    	return clientMap.get(esCode);
    	
    	
    }
    
}
